<?php

declare (strict_types=1);

namespace app\controller\admin;

use think\facade\View;
use think\facade\Request;

class Lang extends Common
{
    public function index($act = '')
    {
        if ($act == 'save') {
            if (!Request::isPost()) {
                return $this->error(lang('参数错误'));
            }
            $langs = input('post.');
            @copy("./app/lang/{$this->lang}.php", "./app/lang/{$this->lang}.bak.php");
            //ksort($langs['langs']);
            $content = "<?php\nreturn " . var_export($langs['langs'], true). ";\n";
            if (!is_writable("./app/lang/{$this->lang}.php")) {
                return error(lang('语言包文件不具有写权限'));
            }
            if (file_put_contents("./app/lang/{$this->lang}.php", $content) !== false) {
                return success(lang('语言包更新成功'), (string) url('admin/lang/index'));
            } else {
                return error(lang('语言包文件不具有写权限'));
            }
        }
        if ($act == 'restore') {
            if (!file_exists("./app/lang/{$this->lang}.bak.php")) {
                return error(lang('无备份文件'));
            }
            @copy("./app/lang/{$this->lang}.bak.php", "./app/index/lang/{$this->lang}.php");
            return success(lang('语言包还原成功'), (string) url('admin/lang/index'));
        }

        if (file_exists("./app/lang/{$this->lang}.php")) {
            $langs = require "./app/lang/{$this->lang}.php";
        } else {
            $langs = require "./app/lang/en-us.php";
        }
        View::assign('langs', $langs);
        return View::fetch();
    }
}
